package com.cheng.common.utils;

import com.cheng.common.exception.CommonException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author: ChengJW
 * @date: 2021/11/2 7:26
 * @version: 1.0
 * @description: 自定义密码加密
 */
public class PswdUtil {

    private final static Logger logger = LoggerFactory.getLogger(PswdUtil.class);

    private static String PASSWORD_CODE = "";

    /**
     * @author: ChengJW
     * @params: []
     * @return:
     * @date: 2021/9/19
     * @description: 私有构造方法，防止工具类被实例化
     */
    private PswdUtil() {
    }

    /**
     * @author: Chengjw
     * @params: [password]
     * @return: java.lang.String
     * @date: 2021/8/5
     * @description: 密码加密，不加盐
     */
    public static String createPswd(String password) throws CommonException{
        return createPswd(null,password);
    }

    /**
     * @author: ChengJW
     * @params: [salt, password]
     * @return: java.lang.String
     * @date: 2021/8/4
     * @description: 自定义密码加密方法，将密码中的每个字符逐个与给出的字符串比较，如果字符串中包含密码字符，则返回索引，并添加到加密字符串中；如果不存在则添加0
     * 再将自定义的盐值按照相同方法，添加到加密字符串
     */
    public static String createPswd(String salt,String password) throws CommonException {
        if (StringUtil.isNull(password)){
            logger.error("密码加密异常:密码不能为空");
            throw new CommonException("CJW202111010017","PswdUtil","createPswd");
        }
        StringBuilder builder = new StringBuilder("");
        String passwordContent = CodeUtil.PASSWORD_SECURITY;
        //将密码和盐拼接成新字符串并转换成字符数组
        char[] pswdChar = (password+salt).toCharArray();
        //遍历密码字符数组
        for (char c : pswdChar){
            //转换成大写
            String c1 = String.valueOf(c);
            //获取当前字符在passwordContent中的位置
            int index = passwordContent.indexOf(c1);
            //当密码字符存在时，将索引位置添加到字符串，当不存在时index=-1，则添加0
            if (index >=0){
                builder.append(index);
            }else {
                builder.append("0");
            }
        }
        return builder.toString();
    }

}
